/*
 * @(#)DbFilter.java   1.0  2021年11月10日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.dts.filter.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Component;

import com.swift.dao.db.datasource.HandlerDataSource;
import com.swift.dts.dao.DbConfigDao;
import com.swift.dts.dao.LogEventTableDao;
import com.swift.dts.dao.model.LogEventTable;
import com.swift.dts.filter.DtsFilter;
import com.swift.dts.loadconfig.model.DtsDataBase;
import com.swift.dts.model.DtsBinlogMessage;
import com.swift.dts.model.SqlObject;
import com.swift.dts.util.CreateExecSql;
import com.swift.util.type.TypeUtil;

/**
 * 添加说明
 * 
 * @author zhengjiajin
 * @version 1.0 2021年11月10日
 */
@Component
@Order
public class DbFilter implements DtsFilter {

    private static final Logger log = LoggerFactory.getLogger(DbFilter.class);

    @Autowired
    private LogEventTableDao logEventTableDao;
    @Autowired
    private DbConfigDao dbConfigDao;
    /**
     * @see com.swift.dts.filter.DtsFilter#filter(com.alibaba.otter.canal.connector.core.consumer.CommonMessage)
     */
    @Override
    public boolean filter(DtsDataBase todb, DtsBinlogMessage message) {
        if (TypeUtil.isNull(message.getExecSqlList())) return true;
        if(!todb.getIsRing()) {
            return false;
        }
        DtsDataBase sdb = dbConfigDao.get(message.getDestination());
        if(sdb==null) {
            return false;
        }
        if(!sdb.getIsRing()) {
            return false;
        }
        for (SqlObject sqlObject : message.getExecSqlList()) {
            boolean filterDML = filterSql(message.getDestination(), sqlObject);
            if (filterDML) return true;
        }
        return false;
    }

    private boolean filterSql(String datasource, SqlObject sqlObject) {
        if (TypeUtil.isNull(sqlObject)) return false;
        try {
            HandlerDataSource.putDataSource(datasource);
            List<LogEventTable> eventTableList = logEventTableDao.listBySqlKey(sqlObject.getUnionKey());
            if (TypeUtil.isNull(eventTableList)) {
                return false;
            }
            for(LogEventTable event:eventTableList) {
                if(CreateExecSql.cleanSql(sqlObject.getSql()).equalsIgnoreCase(CreateExecSql.cleanSql(event.getSqlStr()))) {
                    return true;
                }
            }
            return false;
        } catch (BadSqlGrammarException ex) {
            // 表不存在的异常不处理
        } catch (Exception ex) {
            log.error("查询环形数据异常", ex);
        } finally {
            HandlerDataSource.clear();
        }
        return false;
    }

}
